#include "mystdio.h"
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <malloc.h>
#include <unistd.h>

MY_FILE *my_fopen(const char *path, const char *mode)
{
  // 读取标志位
  int flag = 0; // 这个标志位只与系统调用有关
  if((strcmp(mode, "r") == 0)) flag |= O_RDONLY;
  else if((strcmp(mode, "w") == 0)) flag |= (O_WRONLY | O_CREAT | O_TRUNC);
  else if((strcmp(mode, "a") == 0)) flag |= (O_WRONLY | O_CREAT | O_APPEND);
  else {  }
  // 打开文件 
  mode_t m = 0666;
  int fd = 0;
  if(flag & O_CREAT) fd = open(path, flag, m);
  else fd = open(path, flag);
  
  if(fd < 0) return NULL;
  // 创建结构体
  MY_FILE* fp = (MY_FILE*)malloc(sizeof(MY_FILE));
  if(fp == NULL)
  {
    close(fd);
    perror("my_fopen:");
    return NULL;
  }
  // 初始化结构体
  fp->fd = fd;
  fp->flags = 0;
  fp->flags |= BUFF_LINE;
  fp->current = 0;
  fp->outputbuffer[0] = 0;

  return fp;
}


int my_fflush(MY_FILE* fp)
{
  assert(fp);
  write(fp->fd, fp->outputbuffer, strlen(fp->outputbuffer));
  
  fp->outputbuffer[0] = 0;
  //fp->current = 0;
  fsync(fp->fd);// 刷新数据到内核缓冲区
  return 0;
}

size_t my_fwrite(const void *ptr, size_t size, size_t nmemb,MY_FILE *stream)
{
  assert(stream);
  // 满了就直接刷新
  if(stream->current == NUM) my_fflush(stream);

  // 根据缓冲区剩余情况，拷贝数据
  size_t user_size = nmemb * size;
  size_t buff_size = NUM - stream->current;
  size_t writen = 0;

  if(buff_size >= user_size)
  {
    memcpy(stream->outputbuffer + stream->current, ptr, user_size);
    stream->current += user_size;
    writen = user_size;
  }else
  {
    memcpy(stream->outputbuffer + stream->current, ptr, buff_size);
    stream->current += buff_size;
    writen = buff_size; 
  }

  // 根据刷新策略，刷新数据
  if(stream->flags & BUFF_LINE)
  {
    if(stream->outputbuffer[stream->current - 1] == '\n') my_fflush(stream);
  }else if(stream->flags & BUFF_ALL)
  {
    if(stream->current == NUM) my_fflush(stream);
  }else 
  {
    // buff_NONE
  }

  return writen;
}

int my_fclose(MY_FILE* fp)
{
  assert(fp);

  if(fp->current > 0) my_fflush(fp);
  close(fp->fd);
  free(fp);
  fp = NULL;

  return 0;
}



